import axios from "axios";
import axiosRetry from "axios-retry";
// import {ElMessage} from 'element-plus'
// import { useRouter } from 'vue-router'
axios.defaults.baseURL = '/api';
// const router = useRouter()
let retryCount = 0;
const customRetryCondition = async (error) => {
   if (axios.isAxiosError(error) && error.response?.status !== 200) {
      //如果后端返回的是403
      if (error.response?.status === 403) {
         // ElMessage.error("登录已过期,请重新登录");
         return false
      }

      //如果后端返回的是401
      if (error.response?.status === 401) {
         await axios.get("/refresh")
         return true
      }

      retryCount++;
      console.log(`第${retryCount}次重试`);
      return (
         error.response?.status >= 500 || (error.response?.status < 500 && error.response?.status !== 401)
      );
   }
   return false
};

axiosRetry(axios, {
   retries: 3,
   retryCondition: customRetryCondition,
   retryDelay: axiosRetry.exponentialDelay
})


export const fetchData = async (endpoint) => {
   try {
      const response = await axios.get(endpoint);
      return response.data;
   } catch (error) {
      if (axios.isAxiosError(error)) {
         switch (error.response.status) {
            case 401:
               console.log("未授权,提示用户需要登陆或者获取新的token");
               break;
            case 404:
               console.log("请求资源未找到");
               break;
            default:
               console.log("其他错误");
         }
      } else {
         console.log("非axios错误");
      }
   } finally {
      console.log("请求结束");
   }
};

export default axios